//
//  FB+Rx.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/20.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import FBSDKLoginKit
import RxSwift

extension Reactive where Base == LoginManager {
    
    func login(permissions: [String], from viewController: UIViewController?) -> Single<LoginManagerLoginResult> {
        
//        return Single.create { [weak base] single -> Disposable in
//            
//        }
        
        
        return Single.create{ [weak base] single -> Disposable in
            base?.logIn(permissions: permissions, from: viewController, handler: { (result, error) in
                if let result = result {
                    if result.isCancelled {
//                        single(Result<LoginManagerLoginResult, any Error>);
//                        single(result, .error(NullError()))
                        single(.failure(NullError()))
                    } else {
                        single(.success(result))
                    }
                } else if let error = error {
                    single(.failure(error))
                } else {
                    single(.failure(NullError()))
                }
            })
            return Disposables.create {
            }
        }
    }
    
}

extension Reactive where Base == GraphRequest {
    
    static func start(graphPath: String, parameters: [String: Any], method: HTTPMethod) -> Single<Any> {
        return Single.create { (single) -> Disposable in
//            Base.ini
            let api = Base.init(graphPath: graphPath, parameters: parameters, httpMethod: method)
            
//            let api = Base.init(graphPath: graphPath, parameters: parameters, httpMethod: method)
//            Base.ini
//            GraphRequestCompletion
//            api.start(completion: <#T##GraphRequestCompletion?##GraphRequestCompletion?##((any GraphRequestConnecting)?, Any?, (any Error)?) -> Void#>)
            
            api.start(completion: { (_, result, error) in
                if let result = result {
                    single(.success(result))
                } else if let error = error {
                    single(.failure(error))
                } else {
                    single(.failure(NullError()))
                }
            })
            return Disposables.create()
        }
    }
    
}
